import axios from 'axios'
export default class UploaderManager {
  constructor(dir, btnId, callback, errCallback) {
    this.dir = dir
    this.btnId = btnId
    this.callback = callback
    this.errCallback = errCallback
    this.uploader = null
    this.isUploader = false
    this.config = null
    this.filePath = ''
    this.fileName = ''
    this.initUploader()
  }
  initUploader() {
    this.uploader = new window.plupload.Uploader({
      multi_selection: false,
      runtimes: 'html5',
      browse_button: this.btnId,
      url: 'http://xinbao.oss-cn-beijing.aliyuncs.com',
      filters: {
        mime_types: [ // 只允许上传图片和zip,rar文件
          { title: '图片文件', extensions: 'jpg,gif,png' }
        ],
        max_file_size: '2mb', // 最大只能上传2mb的文件
        prevent_duplicates: true // 不允许选取重复文件
      },
      init: {
        PostInit: () => {},
        FilesAdded: (up, files) => {
          // only allow one file
          if (up.files.length <= 1) {
            return
          }
          up.files.forEach(item => {
            up.removeFile(item)
          })
        },
        BeforeUpload: (up, files) => {
          this.setUploadParam(files.name)
        },
        UploadProgress: (up, files) => {},
        FileUploaded: (up, files, info) => {
          this.isUploading = false
          this.callback(this.config.host + '/' + this.dir + '/' + this.filePath + '/' + this.fileName)
        },
        Error: (up, err) => {
          this.isUploading = false
        }
      }
    })
    this.uploader.init()
  }
  startUpload() {
    if (this.uploader.files.length === 0) {
      if (this.errCallback) {
        this.errCallback('请先选择文件')
      }
      return true
    }
    if (this.isUploading) {
      return false
    }
    this.isUploading = true
    this.getCode()
    return true
  }
  setUploadParam(filename) {
    let name = filename
    if (name) {
      name = this.calculateObjectName(name) + '${filename}'
      this.fileName = filename
    }
    let multipartParams = {
      key: name,
      policy: this.config.policy,
      OSSAccessKeyId: this.config.accessid,
      'success_action_status': '200',
      signature: this.config.signature
    }
    this.uploader.setOption({
      url: this.config.host,
      'multipart_params': multipartParams
    })
    this.uploader.start()
  }
  calculateObjectName(filename) {
    let time = new Date()
    let timeStr = time.getTime().toString()
    this.filePath = timeStr
    return this.dir + '/' + timeStr + '/'
  }
  getCode() {
    axios.post('/ali/key/code', {
      dir: this.dir + '/'
    }).then(data => {
      if (data.data.httpCode === 200) {
        this.config = data.data.data
        this.setUploadParam('')
      } else {}
    }).catch(err => {
      console.log(err)
    })
  }
}
